<template>
  <!-- 操作按钮组 -->
  <!-- <div class="controls">
      <button @click="toggleMarkMode" :class="{ active: markMode }">
        {{ markMode ? "退出标记" : "添加标记" }}
      </button>
      <button @click="toggleDeleteMode" :class="{ active: deleteMode }">
        {{ deleteMode ? "退出删除" : "删除标记" }}
      </button>
      <button @click="toggleEditMode" :class="{ active: editMode }">
        {{ editMode ? "退出编辑" : "编辑标记" }}
      </button>
    </div> -->

  <!-- 地图容器 -->
  <div class="map" id="map"></div>
</template>
  
<script setup>
import { Scene, ImageLayer, Marker } from "@antv/l7";
import { Map } from "@antv/l7-maps";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
const zoom = ref(2.555);
zoom.value = 0.3 + (window.innerHeight / 1305) * 1.855;
const map = reactive({});
const markMode = ref(false);
const deleteMode = ref(false);
const editMode = ref(false);

// 标记点数据
const markers = ref([]);
const markersRef = reactive({});

// 修复问题：确保加载时localStorage有初始值
const initializeStorage = () => {
  if (!localStorage.getItem("mapMarkers")) {
    localStorage.setItem("mapMarkers", "[]");
  }
};
const emit = defineEmits(["marker-clicked"]);
const initMap = () => {
  // 初始化本地存储
  initializeStorage();

  map.scene = new Scene({
    id: "map",
    logoVisible: false,
    map: new Map({
      center: [500, 500],
      pitch: 0,
      zoom: zoom.value,
      version: "SIMPLE",
      mapSize: 1000,
      maxZoom: 5,
      minZoom: 1,
      pitchEnabled: false,
      rotateEnabled: false,
    }),
  });

  map.imagelayer = new ImageLayer({}).source("https://ossdemo.ajioang.cn/mapLeft.webp", {
    parser: {
      type: "image",
      extent: [270, 284, 730, 716],
    },
  });

  map.scene.on("loaded", () => {
    map.scene.addLayer(map.imagelayer);
    loadMarkersFromStorage();
  });
};

// 修复问题：正确读取存储的标记点
const loadMarkersFromStorage = () => {
  try {
    // const savedMarkers = localStorage.getItem("mapMarkers");
    const savedMarkers = [
      {
        id: "marker_1750832999337",
        lng: -1.3249307053040624,
        lat: -1.7341362898807233,
      },
      {
        id: "marker_1751206154549",
        lng: 12.599561327736325,
        lat: 28.784459641202886,
      },
    ];
    if (savedMarkers) {
      markers.value = savedMarkers;

      // 修复问题：确保坐标是数字类型
      markers.value = markers.value.map((marker) => ({
        ...marker,
        lng: Number(marker.lng),
        lat: Number(marker.lat),
      }));

      markers.value.forEach(addMarkerToMap);
    }
  } catch (e) {
    console.error("Error loading markers:", e);
    // 如果解析出错，重置为默认空数组
    markers.value = [];
    saveMarkersToStorage();
  }
};

// 添加标记点到地图
const addMarkerToMap = (marker) => {
  if (isNaN(marker.lng) || isNaN(marker.lat)) {
    console.error("Invalid marker coordinates:", marker);
    return;
  }

  // 创建自定义标记容器
  const markerContainer = document.createElement("div");
  markerContainer.className = "marker-container";

  // 创建标记元素
  const el = document.createElement("div");
  el.className = "custom-marker";
  const size = 30 + Math.floor(Math.random() * 20);
  el.style.width = `${size}px`;
  el.style.height = `${size}px`;

  // 添加图片
  const img = document.createElement("img");
  img.src = "/images/markerLeft.png";
  img.style.width = "100%";
  img.style.height = "100%";
  el.appendChild(img);

  // 创建烟花容器
  const fireworksContainer = document.createElement("div");
  fireworksContainer.className = "fireworks-container";

  // 添加到容器
  markerContainer.appendChild(el);
  markerContainer.appendChild(fireworksContainer);

  // 创建L7标记实例
  const markerInstance = new Marker({
    draggable: editMode.value,
    element: markerContainer,
    offset: [-size / 2, -size / 2],
  })
    .setLnglat([marker.lng, marker.lat])
    .addTo(map.scene);

  markersRef[marker.id] = markerInstance;

  // 添加鼠标事件
  el.addEventListener("click", (e) => handleMarkerClick(e, marker.id));
  el.addEventListener("mouseenter", (e) =>
    triggerFireworks(fireworksContainer)
  );

  markerInstance.on("dragend", (e) => handleMarkerDragEnd(e, marker.id));
};
// 触发烟花特效
const triggerFireworks = (container) => {
  container.innerHTML = "";

  // 波纹数量
  const rippleCount = 5;
  for (let i = 0; i < rippleCount; i++) {
    const ripple = document.createElement("div");
    ripple.className = "ripple";

    // 波纹大小初始为0，逐渐变大
    const size = 40 + i * 20; // 初始大小和间隔
    // const size = 40 + i * 20; // 初始大小和间隔
    ripple.style.width = `${size}px`;
    ripple.style.height = `${size}px`;

    // 设置动画延迟，每个波纹依次出现
    ripple.style.animationDelay = `${i * 0.5}s`;

    container.appendChild(ripple);

    // 动画结束后移除元素
    setTimeout(() => ripple.remove(), i * 500 + 1500);
  }
};

// 移除标记点
const removeMarker = (id) => {
  if (markersRef[id]) {
    markersRef[id].remove();
    delete markersRef[id];
  }

  markers.value = markers.value.filter((m) => m.id !== id);
  saveMarkersToStorage();
};

// 保存标记点到本地存储
const saveMarkersToStorage = () => {
  localStorage.setItem("mapMarkers", JSON.stringify(markers.value));
};

// 处理地图点击事件
const handleMapClick = (e) => {
  if (markMode.value) {
    const newMarker = {
      id: `marker_${Date.now()}`,
      // 修复问题：使用正确的字段名
      lng: e.lngLat.lng,
      lat: e.lngLat.lat,
    };

    markers.value.push(newMarker);
    addMarkerToMap(newMarker);
    saveMarkersToStorage();
  }
};

// 处理标记点点击事件 (添加id参数)
const handleMarkerClick = (e, id) => {
  if (deleteMode.value) {
    removeMarker(id);
    return;
  }

  const markerData = markers.value.find((m) => m.id === id);
  if (markerData) {
    emit("marker-clicked", markerData); // 触发自定义事件
  }
};

// 关键修复：正确处理拖拽结束事件并保存位置
const handleMarkerDragEnd = (e, id) => {
  console.log(e);
  // 只有在编辑模式下才保存拖拽结果
  if (editMode.value) {
    const markerId = id;
    const index = markers.value.findIndex((m) => m.id === markerId);

    if (index !== -1) {
      // 更新内存中的坐标
      markers.value[index].lng = e.lng;
      markers.value[index].lat = e.lat;

      console.log(
        `Saving new position for marker ${id}:`,
        markers.value[index]
      );

      // 保存到本地存储
      saveMarkersToStorage();
    }
  }
};

// 标记模式切换（修复问题：正确切换退出状态）
const toggleMarkMode = () => {
  // 如果当前已经是标记模式，则退出该模式
  if (markMode.value) {
    markMode.value = false;
  }
  // 否则，进入标记模式，退出其他模式
  else {
    deleteMode.value = false;
    editMode.value = false;
    markMode.value = true;
  }

  setupEventListeners();
};

// 删除模式切换（修复问题：正确切换退出状态）
const toggleDeleteMode = () => {
  if (deleteMode.value) {
    deleteMode.value = false;
  } else {
    markMode.value = false;
    editMode.value = false;
    deleteMode.value = true;
  }

  setupEventListeners();
};

// 编辑模式切换（修复问题：正确切换退出状态）
const toggleEditMode = () => {
  if (editMode.value) {
    editMode.value = false;
  } else {
    markMode.value = false;
    deleteMode.value = false;
    editMode.value = true;
  }

  setupEventListeners();
  updateMarkerDraggability();
};

// 设置事件监听器
const setupEventListeners = () => {
  cleanupEventListeners();

  if (markMode.value) {
    map.scene.on("click", handleMapClick);
  }

  // 如果是删除或编辑模式，不需要额外的事件监听
  // 因为标记点事件已经在addMarkerToMap中单独绑定
};

// 清理事件监听器
const cleanupEventListeners = () => {
  map.scene.off("click", handleMapClick);
};

// 更新标记点的可拖拽状态
const updateMarkerDraggability = () => {
  markers.value.forEach((marker) => {
    if (markersRef[marker.id]) {
      // 设置是否可拖拽
      markersRef[marker.id].setDraggable(editMode.value);

      // 即使退出编辑模式，仍然保留拖拽事件监听
      // 因为事件处理中会检查当前是否处于编辑模式
    }
  });
};

onMounted(() => {
  initMap();
});

onBeforeUnmount(() => {
  cleanupEventListeners();

  if (map.scene) {
    map.scene.destroy();
  }
});
</script>
  
<style lang="less">
.map {
  position: relative;
  height: 100vh;
  aspect-ratio: 4593 / 4286;
  touch-action: none;
}

.controls {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1000;
  display: flex;
  gap: 8px;

  button {
    padding: 6px 12px;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    border: 1px solid #555;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;

    &:hover {
      background: rgba(50, 50, 50, 0.8);
    }

    &.active {
      background: #1890ff;
      border-color: #1890ff;
    }
  }
}

.custom-marker {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transform: translate(0, 50%) !important;
  will-change: transform, width, height;
  backface-visibility: hidden;
  transition: transform 0.2s, width 0.2s, height 0.2s;

  img {
    width: 100%;
    height: 100%;
    pointer-events: none;
    /* 确保图片不阻挡事件 */
    position: relative;
  }
}

.fireworks-container {
  position: absolute;
  left: 50%;
  /* 修正定位基准 */
  top: 100%;
  transform: translate(-50%, -50%);
}

.ripple {
  position: absolute;
  border-radius: 50%;
  animation: rippleEffect 1s ease-out;
  transform-origin: 50% 50%;
  border: 4px solid #fdd55e;
  background: rgba(255, 202, 40, 0.2);
  opacity: 0;
  pointer-events: none;
  left: 0;
  top: 0;
}

@keyframes rippleEffect {
  0% {
    transform: translate(-50%, -50%) scale(0);
    opacity: 1;
  }

  100% {
    transform: translate(-50%, -50%) scale(1.5);
    opacity: 0;
  }
}
</style>